package tpsi.pong;

import java.util.Iterator;
import java.util.Set;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;

import org.xlightweb.IWebSocketConnection;

public class PlayerManager {
	private ConcurrentHashMap<Long, Player> players;
	private IDGenerator gen;

	public PlayerManager() {
		this.players = new ConcurrentHashMap<Long, Player>();
		this.gen = new IDGenerator();
	}

	/**
	 * Creates new Player instance with unique id and stores it HashMap.
	 * 
	 * @return Created Player.
	 */
	public Player cratePlayer() {
		Long id = Long.valueOf(gen.getNextID());
		Player p = new Player(Long.valueOf(id));
		this.players.put(id, p);
		return p;
	}

	public void addPlayer(Player p) {
		this.players.put(Long.valueOf(p.getPlayerID()), p);
	}

	/**
	 * Returns Player instance by its unique id. Or null if not found.
	 * 
	 * @param id
	 *            Unique identifier
	 * @return Player instance or null if not found.
	 */
	public Player getPlayerById(Long id) {
		return this.players.get(id);
	}
	
	public Player getPlayerByConnection(IWebSocketConnection con) {
		Player p = null;
		Set<Long> keys = this.players.keySet();
		for (Long l : keys) {
			Player pl = this.players.get(l);
			if (con.equals(pl.getConection())) {
				p = pl;
				break;
			}
		}
		return p;
	}

	/**
	 * Cleans list from disconnected players.
	 */
	public void clean() {
		long timeStamp = System.currentTimeMillis();
		for (Iterator<Entry<Long, Player>> it = this.players.entrySet()
				.iterator(); it.hasNext();) {
			Entry<Long, Player> pair = it.next();
			Player p = pair.getValue();
			if (p.forDeletion(timeStamp))
				it.remove();
		}
	}
	
	public Set<Entry<Long, Player>> getPlayersEntrySet() {
		return this.players.entrySet();
	}
}
